package com.lmy.rabbitmq.work.fair;

import com.rabbitmq.client.*;

import java.io.IOException;

public class Worker2 {

    public static void main(String[] args) {
        //所有的中间件技术都是基于tcp/ip协议基础之上构建新型的协议规范，只不过rabbitmq遵循的是amqp
        //ip port
        //1.创建连接工厂
        ConnectionFactory connectionFactory = new ConnectionFactory();
        connectionFactory.setHost("169.254.27.100");
        connectionFactory.setPort(5672);
        connectionFactory.setUsername("admin");
        connectionFactory.setPassword("admin");
        //可以设置虚拟节点
        connectionFactory.setVirtualHost("/");
        Connection connection = null;
        Channel channel = null;
        try {
            //2.创建连接Connection
            connection = connectionFactory.newConnection("消费者2");
            //3.通过连接获取通道Channel
            channel = connection.createChannel();
            Channel finalChannel = channel;
            //qos表示每次向队列中取多少条数据进行消费
            //finalChannel.basicQos(1) 表示设置该消费者在接收到队列里的消息但没有返回确认结果之前，不会将新的消息分发给它
            finalChannel.basicQos(1);
            //4.接收消息，指定队列名进行消息接收
            channel.basicConsume("workQueue", false, new DeliverCallback() {
                @Override
                public void handle(String s, Delivery delivery) throws IOException {
                    try {
                        System.out.println("worker2接收到消息: " + new String(delivery.getBody(), "UTF-8"));
                        Thread.sleep(2000);
                        //手动ACK
                        finalChannel.basicAck(delivery.getEnvelope().getDeliveryTag(), false);
                    } catch (InterruptedException e) {
                        throw new RuntimeException(e);
                    }
                }
            }, new CancelCallback() {
                @Override
                public void handle(String s) throws IOException {
                    System.out.println("worker2消息接收失败.....");
                }
            });
            System.out.println("Worker2开始接收消息...");
            System.in.read();
        }  catch (Exception e) {
            e.printStackTrace();
        } finally {
            //5.关闭通道
            if (channel != null && channel.isOpen()) {
                try{
                    channel.close();
                }catch (Exception e){
                    e.printStackTrace();
                }
            }
            //6.关闭连接
            if (connection != null && connection.isOpen()) {
                try{
                    connection.close();
                }catch (Exception e){
                    e.printStackTrace();
                }
            }
        }
    }
}
